//
//  TimerView.m
//  Memory
//
//  Created by macvivi on 2021/7/17.
//  Copyright © 2021 yangyang. All rights reserved.
//

#import "TimerView.h"
#import "UIView+Frame.h"
#import "NSTimer+WeakTimer.h"

@implementation TimerView{
    UILabel *_label;
}

- (instancetype)init{
    self = [super init];
    [self setupUI];
    //3.1.2.1 会产生内存泄漏，多次添加TimerView和timer
//    [NSTimer scheduledTimerWithTimeInterval:3.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
//        NSLog(@"timerBlock:%@",timer);
//            int num = [_label.text intValue];
//        num++;
//        [_label setText:[NSString stringWithFormat:@"%d",num]];
//
//    }];
    
    //3.1.2.2 使用中间变量不会产生内存泄漏的问题 NSTimer+WeakTimer.h
    [NSTimer scheduledWeakTimerWithTimeInterval:3.0 target:self selector:@selector(timerFunc) userInfo:nil repeats:YES];
    return  self;
}

- (void)timerFunc{
    NSLog(@"timerFunc");
        int num = [_label.text intValue];
    num++;
    [_label setText:[NSString stringWithFormat:@"%d",num]];
}

- (void)setupUI{
    self.backgroundColor = [UIColor yellowColor];
    self.frame =  CGRectMake(100, 100, 100, 100);
    
    UILabel *label = [UILabel new];
    _label = label;
    [label setText:@"1"];
    [label setTextColor:[UIColor blackColor]];
    label.width = 50;
    label.height = 20;
    label.center = CGPointMake(50, 50);
    [self addSubview:label];
}

- (void)dealloc{
    NSLog(@"timerView dealloc");
}
@end
